#include "ConstrainedTextInputDialog.h"
#include "ui_ConstrainedTextInputDialog.h"
#include <QRegExpValidator>
#include <QPushButton>

ConstrainedTextInputDialog::ConstrainedTextInputDialog(
            QWidget *parent,
            const QString &title,
            const QString &label,
            const QString &initialText,
            const QRegExp &constraint
            ) :
            QDialog(parent),
            m_ui(new Ui::ConstrainedTextInputDialog),
            m_valid(false) {
    m_ui->setupUi(this);
    setWindowTitle(title);
    m_ui->lblText->setText(label);
    m_ui->linValue->setText(initialText);
    m_ui->linValue->setValidator(new QRegExpValidator(constraint, this));
    m_ui->linValue->selectAll();
    connect( m_ui->linValue, SIGNAL(textChanged(QString)),
             SLOT(updateUi()) );
    connect( m_ui->linValue, SIGNAL(returnPressed()),
             SLOT(returnPressed()) );
    updateUi();
}

ConstrainedTextInputDialog::~ConstrainedTextInputDialog() {
    delete m_ui;
}

QString ConstrainedTextInputDialog::textValue() const {
    return m_ui->linValue->text();
}

void ConstrainedTextInputDialog::updateUi() {
    int pos;
    QString text = m_ui->linValue->text();
    QValidator::State state = m_ui->linValue->validator()->validate(text, pos);
    m_valid = state == QValidator::Acceptable;
    m_ui->bnbButtons->button(QDialogButtonBox::Ok)->setEnabled(m_valid);
}

void ConstrainedTextInputDialog::returnPressed() {
    if (m_valid) {
        accept();
    }
}
